package com.hoopchina.ui.main;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import com.hoopchina.news.R;

/**
 * TabBar
 * 应用下边的按钮bar
 * 
 * @author Neusoft
 */
public class TabBar extends UIWidget {
    private TabBarButton[]     mButtons;                   // tab bar buttons
    private int[]              mButtonImgResourceIds;      // image resources
    private int[]              mButtonStringResourceIds;   // string resources
    private int                mFocusedButtonIndex       = TabBarButtonId.EMax;  // current focused button index
    private int                mHiddenCount;
    private int                mButtonCount;
    private final int          mWidth                    = 320;
    private final int          mHeight                   = 480;
    private final int          mAnimDuration             = 400;
    private int                mButtonWidth;
    private int                mButtonHeight;
    private int                mMiddleImageSize;
    LinearLayout.LayoutParams  mButtonLayout;
    LinearLayout               mButtonContainer;
//    ImageView                  mImgHighlight;
    boolean                    mAnimEnabled;

    // constructor
	public TabBar(Context context) {
		super(context);
	}

    // constructor
	public TabBar(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * 加载bar上按钮的图片和其他资源
	 */
	@Override
	protected void loadResources() {
		LayoutInflater inflater = 
			( LayoutInflater )getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
		inflater.inflate( R.layout.tabbar, this, true );
		
//		mImgHighlight = ( ImageView )findViewById( R.id.imgHighlight );
		mButtonContainer = ( LinearLayout )findViewById( R.id.wrapperTabBar );
		
		mButtonWidth = 60;
		mButtonHeight = 40;
		mMiddleImageSize = 35;
		mButtonCount = 5;

		mButtonImgResourceIds = new int[]
				 { R.drawable.image_tabbar_button_news_home	, R.drawable.image_tabbar_button_news_home_selected,  R.drawable.image_tabbar_button_news_home_down,
				   R.drawable.image_tabbar_button_subscription, R.drawable.image_tabbar_button_subscription_selected, R.drawable.image_tabbar_button_subscription_down,
				   R.drawable.image_tabbar_button_hot_news, R.drawable.image_tabbar_button_hot_news_selected,R.drawable.image_tabbar_button_hot_news_down,
				   R.drawable.image_tabbar_button_financial_index, R.drawable.image_tabbar_button_financial_index_selected,R.drawable.image_tabbar_button_financial_index_down,
				   R.drawable.image_tabbar_button_search_news, R.drawable.image_tabbar_button_search_news_selected,R.drawable.image_tabbar_button_search_news_down,
				 };
		mButtonStringResourceIds = new int[]
		         { R.string.app_tabbar_news_home,
				   R.string.app_tabbar_subscription,
				   R.string.app_tabbar_hot_news,
				   R.string.app_tabbar_financial_index,
				   R.string.app_tabbar_search_news
				 };
	   	mButtons = new TabBarButton[mButtonCount];
		///calculateSize();
		//mButtonLayout = new LinearLayout.LayoutParams( mButtonWidth, mButtonHeight );
    	for( int i = 0; i < mButtons.length; ++i ) {
            createButton( i );
    	}
	}
	/*
	 * 设置动画状态
	 */
	public void setAnimEnabled( boolean aEnabled ) {
		mAnimEnabled = aEnabled;
		for ( TabBarButton button : mButtons ) {
			button.setAnimEnabled( mAnimEnabled );
		}
	}
    
	/**
	 * 设置当前选择的按钮的状态
	 */
    public void setFocusedButton( int aIndex ) {
    	if ( aIndex < TabBarButtonId.EMax ) {
    		if ( mAnimEnabled ) {
    			performHighlightAnim( mFocusedButtonIndex, aIndex );
    		}
	    	mFocusedButtonIndex = aIndex;
	    	for( int i = 0; i < mButtons.length; ++i ) {
	    		mButtons[i].setFocused( i == aIndex );
	    	}
    	}
    }
    
    /**
     * 获得当前选中按钮的id
     */
    public int getFocusedButtonIndex() {
    	return mFocusedButtonIndex;
    }
    
    /*
     * 根据id隐藏相应按钮
     */
    public void hideButtonById( int aButtonIndex ) {
    	if ( aButtonIndex >= 0 && aButtonIndex < mButtons.length ) {
	    	TabBarButton button = mButtons[ aButtonIndex ];
	    	if ( button != null ) {
	    		button.setVisibility( View.GONE );
	    		mHiddenCount++;
	    	}
    	}
    	resizeButtons();
    }
    
    /**
     * Set decoration icon position and image
     * @param aId which button the icon will be on
     * @param aImageSource image source
     */
    public void setDecorIcon( int aButtonIndex, int aImageSource, String aMessage ) {
    	TabBarButton button = mButtons[ aButtonIndex ];
    	if ( button != null ) {
    		button.setDecorIcon( aImageSource, aMessage );
    	}
    }
    
    /**
     * Hide decoration icon on specific button
     * @param aId
     */
    public void hideDecorIcon( int aButtonIndex ) {
    	TabBarButton button = mButtons[ aButtonIndex ];
    	if ( button != null ) {
    		button.hideDecorIcon();
    	}
    }

    /**
     * Create a button and add it to tab bar
     * @param aIndex button sequence number
     */
	private void createButton( final int aIndex ) {
		// java doesn't support closure! 
		//	 we have to split this function off from the loop in loadResources()
		TabBarButton button = new TabBarButton( mContext );
		button.setButtonProperties(
				mButtonImgResourceIds[3 * aIndex],
				mButtonImgResourceIds[3 * aIndex + 1],
				mButtonImgResourceIds[3 * aIndex + 2],
				new OnClickListener() {
		        	public void onClick( View v ) {
		        		notifyEvent( aIndex );
		        		// not set focused button here, because main activity will process the event
		        		//   and it has chance that new view will not be switched to
		        	}
		        } );
		button.setButtonText(
				mContext.getString( mButtonStringResourceIds[ aIndex ] ),
				mContext.getResources().getColor( R.drawable.tabbar_normal ),
				mContext.getResources().getColor( R.drawable.tabbar_normal ) );
		button.setBackground( 0, R.drawable.tabbar_selected_background );

        mButtons[aIndex] = button;
        mButtonContainer.addView( mButtons[aIndex] );
	}
    
    /**
     * Resize buttons
     */
    private void resizeButtons() {
    	for ( TabBarButton button : mButtons ) {
    		LinearLayout.LayoutParams layout 
    			= ( LinearLayout.LayoutParams )button.getLayoutParams();
    		layout.width = mWidth / ( mButtonCount - mHiddenCount );
    		button.setLayoutParams( layout );
    	//	button.setChildLayoutParams();
    	}
    }
    
    /**
     * Caculate button size according to current screen resolution
     */
	private void calculateSize() {
		Context context = getContext();
		if ( context instanceof Activity ) {
			DisplayMetrics metrics = new DisplayMetrics();   
			( ( Activity )context ).getWindowManager()
				.getDefaultDisplay().getMetrics( metrics );
			mButtonWidth = metrics.widthPixels / mWidth * mButtonWidth;
			mButtonHeight = metrics.heightPixels / mHeight * mButtonHeight;
			mMiddleImageSize = metrics.widthPixels / mWidth * mMiddleImageSize;
			
//			RelativeLayout.LayoutParams layout 
//				= ( RelativeLayout.LayoutParams )mImgHighlight.getLayoutParams();
//			layout.width = mButtonWidth;
//			layout.height = mButtonHeight;
//			mImgHighlight.setLayoutParams( layout );
		}
	}
	
	private void performHighlightAnim( int aFrom, int aTo ) {
		TranslateAnimation anim = new TranslateAnimation( 
				aFrom * mButtonWidth, aTo * mButtonWidth, 0, 0 );
		anim.setDuration( mAnimDuration );
		anim.setFillAfter( true );
//		mImgHighlight.startAnimation( anim );
	}
}
